package com.cah.project.core.dict.handler;

import cn.hutool.core.util.ClassUtil;
import com.cah.project.core.dict.annotation.DictType;
import com.cah.project.core.dict.cache.NoClearCache;
import com.cah.project.core.dict.domain.vo.DictDataOptions;
import com.cah.project.core.dict.enums.IDictEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Set;

@Slf4j
@Component
public class DictEnumHandler extends AbstractDictHandler {

    @Value("${dict.enum.package:com.cah.project}")
    private String packageStr;

    public DictEnumHandler() {
        cacheData = new NoClearCache<>();
    }

    @Override
    public List<DictDataOptions> getDictDataOptions(String typeCode) {
        return cacheData.get(typeCode);
    }

    @Override
    public void loadDictCache() {
        try {
            // 如果没有数据，进行注册
            Set<Class<?>> classes = ClassUtil.scanPackageBySuper(packageStr, IDictEnum.class);
            for (Class<?> aClass : classes) {
                if (ClassUtil.isEnum(aClass)) {
                    DictType dictType = aClass.getAnnotation(DictType.class);
                    if (dictType == null) {
                        throw new RuntimeException("枚举：" + aClass.getName() + " 没有添加@DictType注解。");
                    }
                    Method codeMethod = ClassUtil.getDeclaredMethod(aClass, "getCode");
                    Method msgMethod = ClassUtil.getDeclaredMethod(aClass, "getMsg");
                    if (codeMethod == null || msgMethod == null) {
                        continue;
                    }
                    //得到enum的所有实例
                    Object[] objList = aClass.getEnumConstants();
                    for (Object obj : objList) {
                        put(dictType.typeCode(), (String) codeMethod.invoke(obj), (String) msgMethod.invoke(obj));
                    }
                    // 添加字典类型
                    addDictType(dictType.typeCode(), dictType.typeName());
                }
            }
        } catch (IllegalAccessException | InvocationTargetException e) {
            log.error("枚举缓存加载异常：{}", e.getMessage());
        }
    }

    @Override
    public void reloadDictCache(String typeCode) {
        // 由于的内存的，不需要重新加载
    }

}
